<template>
    <!-- <div> -->
        <div class="fav-component">
            <div class="fav-header">
                收藏 <a class="close-win" @click="handleClose"></a>
            </div>
            <div class="folder-con">
                <div class="tit">选择文件夹</div>
                <div class="search-bx">
                    <form @submit.prevent="()=>{return false;}">
                        <input type="text" v-model="searchkey" placeholder="搜索" />
                    </form>
                </div>
                <div class="folders">
                    <div class="folder-item" v-for="(f,idx) in list" :key="idx" v-if="f.show" @click="handleToSaveFav(f)">
                        <div class="left">
                            <span class="img-box">
                                <img loading="lazy" :src="f.thumbnailList[0]" alt="" v-if="f.thumbnailList&&f.thumbnailList.length>0">
                            </span>
                            <span class="title-text" :title="f.title">{{f.title}}</span>
                        </div>
                        <a class="fav-btn">收藏</a>
                    </div>
                    <div class="no-result" v-if="selectLen==0">暂无相关数据~</div>
                </div>
                <a class="create-new-folder" @click="showCreate=true">
                    <span>新建{{folderTypeEnum[foldertype]}}文件夹</span>
                </a>
            </div>

            <a-modal v-model="showCreate" destroyOnClose centered :footer="null"  :closable="false">
                <CreateFolder @close="onRefresh" :foldertype="foldertype" />
            </a-modal>
        </div>
        <!-- <div class="modal-mask" @click="handleClose">

        </div> -->
    <!-- </div> -->
</template>

<script>
import api from '@/api/api'
import CreateFolder from '@/components/CreateFolder'
export default {
    components:{CreateFolder},
    data(){
        return {
            searchkey:'',
            folderTypeEnum:{
                1:'图片集收藏夹',
                0:'单图收藏夹',
                2:'短视频收藏夹'
            },
            showCreate:false,
            list:[],
            params:{
                pageNum:1,
                pageSize:20,
                orderByColumn:'createTime',
                isAsc:'desc'
            },
            starParam:{
                isAnimating:false,
                lastTime:0,
                CONFIG:{
                    particleCount: {
                        mobile: 15,
                        tablet: 20, 
                        desktop: 25
                    },
                    cooldown: 1500
                }
            }
        }
    },
    computed:{
        selectLen(){
            return this.list.filter(r=>{
                return r.show==true;
            }).length
        }
    },
    watch:{
        searchkey(newd){
            this.list.map(item=>{
                if(item.title.indexOf(newd)>-1){
                    item.show=true;
                }else{
                    item.show=false;item.showOther=false;
                }
            })
        }
    },
    props:['foldertype','imgids','articleid','ismove','collectIds','favmodule','favmodules'],
    methods:{
        handleClose(){
            this.$emit('close')
        },
        onRefresh(isRefresh){
            this.showCreate=false;
            if(isRefresh)
            {
                this.params.pageNum=1;
                this.list=[];
                this.queryList();
            }
        },
        async queryList(){
            let res=await api.explorerList(this.params);
            // if(this.foldertype==1){
            //     this.params.type=1;
            //     res=await api.getMutiplePicFavs(this.params);
            // }else if(this.foldertype==2){
            //     this.params.type=2;
            //     res=await api.getNewFavFolds(this.params);
            // }else if(this.foldertype==3){
            //     res=await api.getVideoFolders(this.params);
            // }
            // let _typeEnum={

            // }
            res.data.map(item=>{
                item.show=true;
            })
            this.list=res.data;
        },
        getRandomNumber(min, max) {
            return Math.random() * (max - min) + min;
        },
        getParticleCount() {
            const width = window.innerWidth;
            if (width <= 480) return this.starParam.CONFIG.particleCount.mobile;
            if (width <= 768) return this.starParam.CONFIG.particleCount.tablet;
            return this.starParam.CONFIG.particleCount.desktop;
        },
        createStars() {
            const confettiContainer = document.createElement('div');
            confettiContainer.className = 'confetti-container';
            
            if(document.querySelector('.img-component')||location.href.indexOf('/imgv/')>-1){
                document.querySelector('.img-component').appendChild(confettiContainer);
            }
            else if(document.querySelector('.game-page')){
                document.querySelector('.game-page').appendChild(confettiContainer);
            }
            else if(document.querySelector('.work')){
                document.querySelector('.work').appendChild(confettiContainer);
            }
            else if(document.querySelector('.comp-article-page')){
                document.querySelector('.comp-article-page').appendChild(confettiContainer);
            }
            else
                document.body.appendChild(confettiContainer);

            const now = Date.now();
            if (this.starParam.isAnimating || now - this.starParamlastTime < this.starParam.CONFIG.cooldown) return;
            
            this.starParam.isAnimating = true;
            this.starParam.lastTime = now;

            // const btn = document.querySelector('.demo-btn');
            // btn.style.animation = 'btn-success 0.5s ease';
            // setTimeout(() => btn.style.animation = '', 500);

            const particleCount = this.getParticleCount();
            const viewportWidth = window.innerWidth;
            const spacing = viewportWidth / particleCount;

            const fragment = document.createDocumentFragment();
            let activeParticles = particleCount;

            for(let i = 0; i < particleCount; i++) {
                const star = document.createElement('div');
                star.className = 'star';
                star.textContent = '⭐';
                
                const xPos = i * spacing + this.getRandomNumber(-20, 20);
                star.style.left = `${xPos}px`;
                
                const duration = this.getRandomNumber(2, 3);
                star.style.animationDuration = `${duration}s`;

                star.addEventListener('animationend', () => {
                    star.remove();
                    if (--activeParticles === 0) {
                        this.starParam.isAnimating = false;
                    }
                }, { once: true });

                fragment.appendChild(star);
            }

            confettiContainer.appendChild(fragment);
        },
        async handleToSaveFav(item){
            let res={};
            let that=this;
            if(this.ismove){//转移到目标文件夹
                if(this.foldertype==0){
                    res= await api.batchCancelMoveSinglePic(item.id,this.collectIds);
                    if(res.code==0){
                        this.createStars();
                        this.$bhelper.addCirRecord('COLLECT-'+this.favmodule);
                        this.$bhelper.addCirRecord('COLLECT');
                        this.$store.dispatch('setLeftMenu',[])
                        this.$amessage.success('已收藏，随时查看哦～')
                        this.$emit('favsucc')
                    }
                }else{
                    res= await api.batchCancelMoveMutipleArticles(item.id,this.imgids);
                    if(res.code==0){
                        this.createStars();
                        if(this.favmodules){
                            this.favmodules.map(fmodule=>{
                                that.$bhelper.addCirRecord('COLLECT-'+fmodule);
                            })
                        }
                        this.$bhelper.addCirRecord('COLLECT');
                        this.$store.dispatch('setLeftMenu',[])
                        this.$amessage.success('已收藏，随时查看哦～')
                        this.$emit('favsucc')
                    }
                }
            }
            else{
                if(this.articleid){
                    res=await api.favArticle({collectId:this.articleid,explorerId:item.id});
                }else{
                    if(this.foldertype==1){
                        res=await api.batchCancelMoveMutipleArticles(item.id,this.imgids);
                    }else if(this.foldertype==0){
                        res=await api.batchToFav(item.id,this.imgids);
                    }else if(this.foldertype==2){
                        res=await api.collectVideo(item.id,this.imgids);
                    }
                }
                if(res.code==0){
                    this.createStars();
                    this.$bhelper.addCirRecord('COLLECT-'+this.favmodule);
                    this.$bhelper.addCirRecord('COLLECT');
                    this.$store.dispatch('setLeftMenu',[])
                    this.$amessage.success('已收藏，随时查看哦～')
                    this.$emit('favsucc')
                }
            }
        }
    },
    destroyed(){
        // document.body.style.overflow='inherit';
    },
    mounted(){
        if(!localStorage.getItem('token')){
            this.$amessage.warn('请先登录~');
            let that=this;
            setTimeout(()=>{
                that.handleClose();
            },800)
            return;
        }
        this.params.type=this.foldertype;
        // document.body.style.overflow='hidden';
        this.queryList();
    }
}
</script>

<style lang="less">
.no-result{
    text-align: center;
    line-height:68px;
    text-align: center;
    color:#8f8f8f;
}
</style>